package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.service.goods.SkuSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SkuSearchServiceImpl implements SkuSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final String SKU_INDEX_NAME = "sku";

    public Map search(Map<String, String> searchMap) {
        SearchRequest searchRequest=new  SearchRequest(SKU_INDEX_NAME);
        searchRequest.types("doc");  //设置查询的类型
        SearchSourceBuilder searchSourceBuilder=new  SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder  =  QueryBuilders.boolQuery();//布尔查询构建器
        MatchQueryBuilder matchQueryBuilder=  QueryBuilders.matchQuery("name", searchMap.get("keywords"));
        boolQueryBuilder.must(matchQueryBuilder);
        if (searchMap.get("category") != null) {
            TermQueryBuilder termQueryBuilder=QueryBuilders.termQuery("categoryname", searchMap.get("category"));
            boolQueryBuilder.filter(termQueryBuilder);
        }

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        TermsAggregationBuilder termsAggregationBuilder =
                AggregationBuilders.terms("sku_category").field("categoryname");
        searchSourceBuilder.aggregation(termsAggregationBuilder);
        TermsAggregationBuilder brandTermsAggregationBuilder =
                AggregationBuilders.terms("sku_brand").field("brandname");
        searchSourceBuilder.aggregation(termsAggregationBuilder);
        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name").preTags("<font style='color:red'>").postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //排序
        String sort = searchMap.get("sort");//排序字段
        String sortOrder = searchMap.get("sortOrder");//排序规则
        if(!"".equals(sort)){
            searchSourceBuilder.sort(sort, SortOrder.valueOf(sortOrder));
        }
        int pageSize = 30;
        int pageNo = Integer.parseInt(searchMap.get("pageNo"));
        int fromIndex = (pageNo - 1) * pageSize;
        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.from(fromIndex);
        searchRequest.source(searchSourceBuilder);
        //3.获取查询结果
        SearchResponse searchResponse = null;
        HashMap map = new HashMap();
        try {
            searchResponse = restHighLevelClient.search(searchRequest,
                    RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            long totalHits = searchHits.getTotalHits();
            System.out.println("记录数："+totalHits);
            long totalPages = (totalHits%pageSize == 0) ? (totalHits/pageSize) : (totalHits/pageSize + 1);
            map.put("totalPages", totalPages);
            SearchHit[] hits = searchHits.getHits();
            List skuList = new ArrayList();

            for(SearchHit hit:hits){

                //提取高亮内容
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlightFieldName = highlightFields.get("name");
                Text[] fragments=highlightFieldName.fragments();
                String name = fragments[0].toString();
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                sourceAsMap.put("name", name);
                skuList.add(sourceAsMap);
            }
            map.put("rows", skuList);
            List<String> categoryList = new ArrayList<String>();
            Aggregations aggregations = searchResponse.getAggregations();
            Map<String, Aggregation> asMap = aggregations.getAsMap();
            Terms terms = (Terms) asMap.get("sku_category");
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            for(Terms.Bucket bucket:buckets){
                categoryList.add(bucket.getKeyAsString());
            }
            List<String> brandList = new ArrayList<String>();
            Aggregations brandAggregations = searchResponse.getAggregations();
            Map<String, Aggregation> bAsMap = brandAggregations.getAsMap();
            Terms brandTerms = (Terms) bAsMap.get("sku_brand");
            List<? extends Terms.Bucket> brandBuckets = brandTerms.getBuckets();
            for(Terms.Bucket bucket : brandBuckets){
                brandList.add(bucket.getKeyAsString());
            }
            map.put("categoryList", categoryList);
            map.put("brandList", brandList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }


}
